<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #icon="{ model, field }">
        <Upload
          v-model:file-list="model[field]"
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <LoadingOutlined v-if="loading" />
            <PlusOutlined v-else />
            <div class="ant-upload-text">上传头像</div>
          </div>
        </Upload>
      </template>
      <template #roleIds="{ model, field }">
        <Select
          v-model:value="model[field]"
          :options="roleData"
          :field-names="{ label: 'roleName', value: 'id' }"
          placeholder="请选择"
          mode="multiple"
          allow-clear
        />
      </template>
      <template #deptIds="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          tree-checkable
          tree-default-expand-all
          :tree-check-strictly="false"
          :tree-data="deptTreeData"
          :field-names="{ label: 'deptName', value: 'id' }"
          placeholder="请选择"
          allow-clear
        />
      </template>
      <template #menuIds="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          tree-default-expand-all
          :tree-check-strictly="false"
          :tree-data="menuTreeData"
          :field-names="{ label: 'menuTitle', value: 'id' }"
          placeholder="请选择"
          allow-clear
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { accountFormSchema } from './account.data';
  import { Select, TreeSelect, Upload, UploadChangeParam, UploadProps } from 'ant-design-vue';
  import { MICRO_SERVICE_FILE_UPLOAD } from '/@/api/ServiceConstant';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import {
    createUser,
    queryDeptTreeList,
    queryMenuTreeList,
    queryRolePage,
    modifyUser,
  } from '/@/api/system/system';
  import { DeptResp } from '/@/api/system/modal/deptModel';
  import { RoleReq, RoleResp } from '/@/api/system/modal/roleModel';
  import { Query } from '/@/api/model/baseModel';
  import { UserReq } from '/@/api/system/modal/userModel';
  import { MenuResp } from '/@/api/system/modal/menuModel';

  export default defineComponent({
    name: 'AccountModal',
    components: {
      BasicModal,
      BasicForm,
      Upload,
      LoadingOutlined,
      PlusOutlined,
      Select,
      TreeSelect,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const userStore = useUserStore();
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      const id = ref('');
      const rowId = ref('');
      const loading = ref(false);
      const imageUrl = ref('');
      const iconId = ref('');

      const userInfo = userStore.getUserInfo;
      const uploadUrl = ref(
        MICRO_SERVICE_FILE_UPLOAD +
          '?x-app-id=turbo-cloud-minio&x-app-key=u6yYo4XF&bucketName=ums-bucket&businessType=UserIcon&businessNo=' +
          userInfo.id +
          '&uploadBy=' +
          userInfo.id,
      );
      const iconFileId = ref('');

      const roleData = ref<RoleResp[]>([]);

      const deptTreeData = ref<DeptResp[]>([]);
      const menuTreeData = ref<MenuResp[]>([]);
      const showParent = TreeSelect.SHOW_PARENT;

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        await resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;
        imageUrl.value = data?.record?.iconFileUrl;
        iconId.value = data?.record?.icon;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          await setFieldsValue({
            ...data.record,
          });
        }

        const roleQuery: Query<RoleReq> = {
          current: 1,
          size: 1000,
        };

        const rolePage = await queryRolePage(roleQuery);
        if (rolePage.records) {
          roleData.value = rolePage.records;
        }

        deptTreeData.value = await queryDeptTreeList();
        menuTreeData.value = await queryMenuTreeList();

        updateSchema([
          {
            field: 'username',
            show: !unref(isUpdate),
          },
        ]);
        updateSchema([
          {
            field: 'password',
            show: !unref(isUpdate),
          },
        ]);
      });

      const beforeUpload = (file: UploadProps['fileList'][number]) => {
        const isJpgOrPng = file.type === 'image/png' || file.type === 'image/jpeg';
        if (!isJpgOrPng) {
          createMessage.warn('请上传图片文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          createMessage.warn('请上传图片文件大小小于2BM');
        }
        return isJpgOrPng && isLt2M;
      };

      const handleChange = (info: UploadChangeParam) => {
        if (info.file.status === 'uploading') {
          loading.value = true;
          return;
        }
        if (info.file.status === 'done') {
          if (
            info.file.response &&
            info.file.response.result &&
            info.file.response.result.fileUrl
          ) {
            imageUrl.value = info.file.response?.result?.fileUrl;
            iconFileId.value = info.file.response?.result?.fileId;
          }
          loading.value = false;
          return;
        }
        if (info.file.status === 'error') {
          loading.value = false;
          createMessage.warn('上传图片文件失败');
        }
      };

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          let icon = iconId.value || '';
          if (values.iconFileList && values.iconFileList[0]) {
            icon = values.iconFileList[0]?.response?.result?.fileId;
          }

          const userReq: UserReq = {
            icon: icon,
            ...values,
          };
          if (unref(isUpdate)) {
            userReq.id = unref(id);
            await modifyUser(userReq);
          } else {
            await createUser(userReq);
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          if (msg) {
            createMessage.error(msg);
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        uploadUrl,
        loading,
        imageUrl,
        beforeUpload,
        handleChange,
        deptTreeData,
        menuTreeData,
        showParent,
        roleData,
        handleSubmit,
      };
    },
  });
</script>
